package com.easy.utils;

import org.apache.commons.codec.digest.DigestUtils;

public class DigestUtil {

    private static final int countIndex = 12;
    private static final int saltIndex = 1;
    private static final char[] items = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    public static String randomDigest(String pass){
        int randomCountIndex = (int)(Math.random()*items.length);
        int randomSaltIndex = (int)(Math.random()*items.length);

        char count = items[randomCountIndex];
        char salt = items[randomSaltIndex];
        System.out.println(salt);
        System.out.println(count);
        String result = pass+salt;

        for(int i = 0; i < count; i++){
            result = DigestUtils.md5Hex(result);
        }
        System.out.println(result);
        //result就是加密之后的字符串
        result = result.substring(0,saltIndex) + salt + result.substring(saltIndex);
        result = result.substring(0,countIndex) + count + result.substring(countIndex);
        System.out.println(result);
        return result;

    }

    //比对密码是否正确
    public static boolean decode(String pass,String digestpass){
        char salt = digestpass.charAt(saltIndex);
        char count = digestpass.charAt(countIndex);

        String result = pass + salt;
        for(int i = 0; i < count; i++){
            result = DigestUtils.md5Hex(result);
        }
        result = result.substring(0,saltIndex) + salt + result.substring(saltIndex);
        result = result.substring(0,countIndex) + count + result.substring(countIndex);

        return result.equals(digestpass);
    }

}
